import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'home',
    component: () => import('@/views/Home.vue'),
    meta: {
      title: '首页',
      requiresAuth: false
    }
  },
  {
    path: '/trade',
    name: 'trade',
    component: () => import('@/views/Trade.vue'),
    meta: {
      title: '套餐与报价',
      requiresAuth: false
    }
  },
  {
    path: '/publish',
    name: 'publish',
    component: () => import('@/views/Publish.vue'),
    meta: {
      title: '信息发布',
      requiresAuth: false
    }
  },
  {
    path: '/member',
    name: 'member',
    component: () => import('@/views/MemberCenter.vue'),
    meta: {
      title: '会员中心',
      requiresAuth: true // 需要登录
    }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, _from, next) => {
  // 更新页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title as string} - 智慧招考平台`
  }

  // 认证检查
  const userStore = useUserStore()
  const requiresAuth = to.meta.requiresAuth as boolean

  if (requiresAuth && !userStore.isLoggedIn) {
    // 需要登录但未登录,跳转到首页并提示
    ElMessage.warning('请先登录')
    next({ path: '/', replace: true })
  } else {
    next()
  }
})

export default router
